# 148. 排序链表

function ListNode(val, next) {
  this.val = val === undefined ? 0 : val;
  this.next = next === undefined ? null : next;
}

var sortList = function(head) {
  if (head === null) return head;

  const start = new ListNode(0);
  start.next = head;
  let last = head,
    curr = head.next;
  while (curr !== null) {
    console.log(curr, last);
    if (last.val <= curr.val) {
      last = last.next;
    } else {
      let prev = start;
      while (prev.next.val <= curr.val) {
        prev = prev.next;
      }
      last.next = curr.next; // 缓存待插入节点
      curr.next = prev.next; // 讲插入节点和下一个节点续接上
      prev.next = curr;
    }

    curr = last.next; // 更新待插入节点
  }

  return JSON.stringify(start.next);
};
// console.log(
//   sortList({
//     val: 4,
//     next: {
//       val: 2,
//       next: {
//         val: 1,
//         next: {
//           val: 3,
//           next: null,
//         },
//       },
//     },
//   })
// );
console.log(
  sortList({
    val: -1,
    next: {
      val: 5,
      next: {
        val: 3,
        next: {
          val: 4,
          next: {
            val: 0,
            next: null,
          },
        },
      },
    },
  })
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
Last Updated: 6/27/2023, 7:40:45 PM